package com.example.gulimall.cart.interceptor;

// 执行方法之前 判断一下他的登陆状态 并传递给handler进行目标请求

import com.example.common.constant.AuthServerConstant;
import com.example.common.constant.CartConstant;
import com.example.common.vo.MemberResponseVo;
import com.example.gulimall.cart.vo.UserInfoTo;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

public class CartInterceptor implements HandlerInterceptor {


    //启动ThreadLocal进行数据共享
    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        UserInfoTo infoTo = new UserInfoTo();

        HttpSession session = request.getSession();
        MemberResponseVo attribute = (MemberResponseVo) session.getAttribute(AuthServerConstant.LOGIN_USER);

        // 获取当前的cartlist
        if(attribute != null)
            infoTo.setUserId(attribute.getId());

        Cookie[] cookies = request.getCookies();
        if(cookies != null && cookies.length > 0){
            for(Cookie cookie: cookies){
                if(cookie.getName().equals(CartConstant.TEMP_USER_COOKIE_NAME)){
                    infoTo.setUserKey(cookie.getValue());
                    infoTo.setTempUser(true); //判断是不是第一次用户
                    break;
                }
            }
        }


        // 如果userkey仍然为空 说明确实是第一次登陆
        if(StringUtils.isEmpty(infoTo.getUserKey())){
            String s = UUID.randomUUID().toString();
            infoTo.setUserKey(s);
        }

        threadLocal.set(infoTo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();
        if(!userInfoTo.getTempUser()){
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME,userInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
